package com.example.bookmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bookmall.entity.Aftersales;
import com.example.bookmall.entity.Result;
import com.example.bookmall.entity.order.Orders;
import com.example.bookmall.mapper.AftersalesMapper;
import com.example.bookmall.mapper.OrderMapper;
import com.example.bookmall.service.AftersalesService;
import com.example.bookmall.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class AftersalesServiceImpl implements AftersalesService {

    @Autowired
    private AftersalesMapper aftersalesMapper;
    @Autowired
    private OrderMapper orderMapper;


    //用户 申请售后
    @Override
    public Result setaftersales(Aftersales aftersales) {

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");

        String orderId =aftersales.getOrderId();

        //根据订单id查询订单 设置订单的状态为售后中

        Orders orders = orderMapper.selectByOrderId(orderId);
        if(orders==null){
            return Result.error("找不到用户订单");
        }

        //设置订单状态为售后中
        orders.setOrderStatus(6);
        orderMapper.updateById(orders);

        aftersales.setUserId(userId);
        aftersales.setOrderId(orderId);
        //设置管理员同意售后为否
        aftersales.setAdminAgreement(0);
        aftersales.setCreateTime(LocalDateTime.now());
        aftersales.setUpdateTime(LocalDateTime.now());


        return Result.success(aftersalesMapper.insert(aftersales));
    }

    @Override
    public Aftersales findByOrderId(String orderId) {
        return aftersalesMapper.selectOne(new QueryWrapper<Aftersales>().eq("order_id",orderId));
    }
}
